<?php

/**
 * Item actions.
 *
 * @package    ProdAssistant
 * @subpackage Item
 * @author     Paweł Świtalla
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class ItemActions extends sfActions
{
  private $core;
  public function preExecute()
  {
    $this->core = PACore::getInstance();
  }
  
  public function executeIndex(sfWebRequest $request)
  {
    $this->forward('Category', 'itemList');
  }
  
  public function executeShow(sfWebRequest $request)
  {
    $itemId = $request->getParameter('id');
    $item = Doctrine_Core::getTable('StoreItem')->find($itemId);
    if($item instanceof Doctrine_Record)
    {
      $this->category = $item->getCategory();
      $this->columns = $this->category->getParametersHierarchy();
      $this->item = array('id' => $item->getId() ,'name' => $item->getName(), 'quantity' => $item->getQuantity(), 'quantityUnit' => $this->category->getQuantityUnit(), 'category' => $item->getCategory()->getName());
      $this->parameters = array();
      
      foreach($this->columns as $column)
      {
        $value = Doctrine_Query::create()
                ->select("s.{$column->getName()}")
                ->from('StoreItem s')
                ->where('s.id = ?', $item->getId())
                ->fetchOne()
                ->toArray();
        $this->parameters[$column->getName()] = array('value' => $value[$column->getName()], 'unit' => $column->getUnit());
      }
    }
    $this->setLayout(PACore::getLayoutsDir().'clear');
  }
  
  public function executeCreate(sfWebRequest $request)
  {
    $formParameters = $request->getParameter('store_item');
    $url = $this->core->generateAppUrl('Store', 'categoryItemsList', true, array('categoryName' => $request->getParameter('category')));
    if(is_array($formParameters))
    {
      $category = '';
      try
      {
        $category = Doctrine_Core::getTable('Category')->findBy('name', $request->getParameter('category'))->getFirst();
      }
      catch(Doctrine_Exception $e)
      {
        $this->error = 'Exeption: '.$e->getMessage();
        $this->setTemplate(PACore::getErrorTemplatesDir().'default');
        return sfView::ERROR;
      }
      $this->form = new StoreItemForm($category->getName());
      $formParameters['category_id'] = $category->getId();

      if($request->isMethod('post'))
      {
        $this->form->bind($formParameters);
        if($this->form->isValid())
        {
          $item = $this->form->save();
          
          foreach($category->getParameters()->toArray() as $parameter => $settings)
          {
            $q = Doctrine_Query::create()
                    ->update('StoreItem')
                    ->set("{$settings['name']}", "?", "{$formParameters[$settings['name']]}")
                    ->where('id = ?', $item->getId())
                    ->execute();
          }
          
          $parents = $item->getParentCategories();
          foreach($parents as $parent)
          {
            $parent->setItemsCount($parent->getItemsCount() + 1)->save();
          }
          
          if($request->isXmlHttpRequest())
          {
            $this->getResponse()->setContent('location@'.$url."#");
            return sfView::NONE;
          }
          else $this->redirect($this->core->generateAppUrl('Store', 'categoryHomepage'));
        }
      }
    }
    if($request->isXmlHttpRequest())
    {
      $errors = '';
      foreach($this->form->getFormFieldSchema() as $field){
        if($field->hasError()){
          $errors .= ucfirst($field->getName()).': '.$field->getError()."\n";
        }
      }
      $this->getResponse()->setContent('error@'.$errors."#");
      return sfView::NONE;
    }
    else $this->referer = $url;
  }
  
  public function executeDelete(sfWebRequest $request)
  {
    $id = $request->getParameter('id');
    $item = Doctrine_Core::getTable('StoreItem')->find($id);
    $parentCategories = $item->getParentCategories();
    $delete = $item->delete();
    
    if($delete)
    {
      foreach($parentCategories as $parent)
      {
        $parent->setItemsCount($parent->getItemsCount() - 1)->save();
      }
    }
    $this->getUser()->setFlash("handler", "window.close");
    $this->redirectIf($delete, $request->getReferer());
  }
  
  public function executeDeleteList(sfWebRequest $request)
  {
    $itemTable = Doctrine_Core::getTable('StoreItem');
    $list = $request->getParameter('items_list');
    if($list && is_array($list))
    {
      foreach($list as $id => $state)
      {
        $item = $itemTable->find($id);
        $parentCategories = $item->getParentCategories();
        foreach($parentCategories as $parent)
        {
          $parent->setItemsCount($parent->getItemsCount() - 1)->save();
        }
        
        $delete = $itemTable->createQuery('i')
                ->delete()
                ->where('i.id = ?', $id)
                ->execute();
      }
    }
    $this->redirect($request->getReferer());
  }
  
  public function executeUpdate(sfWebRequest $request)
  {
    $formParameters = $request->getParameter('store_item');
    $url = $this->core->generateAppUrl('Store', 'categoryItemsList', true, array('categoryName' => $request->getParameter('category')));
    if(is_array($formParameters))
    {
      $category = '';
      try
      {
        $category = Doctrine_Core::getTable('Category')->findBy('name', $request->getParameter('category'))->getFirst();
      }
      catch(Doctrine_Exception $e)
      {
        $this->error = 'Exeption: '.$e->getMessage();
        $this->setTemplate(PACore::getErrorTemplatesDir().'default');
        return sfView::ERROR;
      }
      $item = Doctrine_Core::getTable('StoreItem')->find($request->getParameter('id'));
      $baseCategory = $item->getCategory();
      
      if($request->isXmlHttpRequest() && (($baseCategory != $category) && $category->getLocked()))
      {
        $this->getResponse()->setContent('error@Edytuj w kategorii bazowej!#');
        return sfView::NONE;
      }
      elseif(($baseCategory != $category) && $category->getLocked()){
        $this->getUser()->setFlash('info', 'Edytuj w kategorii bazowej');
        $this->redirect($this->core->generateAppUrl('Store', 'categoryHomepage'));
      }
      
      $this->form = new StoreItemForm($category->getName(), array(), $item);
      $formParameters['category_id'] = $category->getId();

      if($request->isMethod('put'))
      {
        $this->form->bind($formParameters);
        if($this->form->isValid())
        {
          $item = $this->form->save();
          
          foreach($category->getParameters()->toArray() as $parameter => $settings)
          {
            $q = Doctrine_Query::create()
                    ->update('StoreItem')
                    ->set("{$settings['name']}", "?", "{$formParameters[$settings['name']]}")
                    ->where('id = ?', $item->getId())
                    ->execute();
          }
          
          if($request->isXmlHttpRequest())
          {
            $this->getResponse()->setContent('location@'.$url."#");
            return sfView::NONE;
          }
          else $this->redirect($request->getReferer());
        }
      }
    }
    if($request->isXmlHttpRequest())
    {
      $errors = '';
      foreach($this->form->getFormFieldSchema() as $field){
        if($field->hasError()){
          $errors .= ucfirst($field->getName()).': '.$field->getError()."\n";
        }
      }
      $this->getResponse()->setContent('error@'.$errors."#");
      return sfView::NONE;
    }
    else $this->referer = $url;
  }
  
  public function executeUpdateWindow(sfWebRequest $request)
  {
    $this->id = $request->getParameter("id");
    $item = Doctrine_Core::getTable("StoreItem")->find($this->id);
    $this->category = $item->getCategory();
    $this->form = new StoreItemForm($item->getCategory()->getName(), array(), $item);
    $this->setLayout(PACore::getLayoutsDir()."/clear");
  }
  
  public function executeCheckQuantity(sfWebRequest $request)
  {
    $result = array();
    if($request->hasParameter('items'))
    {
      $items = $request->getParameter('items');
      if(count($items))
      {
        foreach($items as $key => $value){
          $item = Doctrine_Core::getTable('StoreItem')->find($key);
          if($item instanceof StoreItem)
          {
            if($item->getQuantity() < $value) $result[$key] = array("quantity" => $item->getQuantity(), "unit" => $item->getCategory()->getQuantityUnit());
          }
        }
      }
    }
    $this->getResponse()->setHttpHeader('Content-Type', 'application/json');
    $this->getResponse()->setContent(json_encode($result));
    return sfView::NONE;
  }
  
  public function executeSearch(sfWebRequest $request)
  {
    $categoryName = $request->getParameter('category');
    
    $categoryTable = Doctrine_Core::getTable('Category');
    $category = $categoryTable->createQuery('c')
              ->select('name')
              ->where('c.name = ?', $categoryName)
              ->fetchOne();

    $this->columnsObjects = $category->getParametersHierarchy();
    $this->columns = array("name" => "Nazwa",
                           "quantity" => "Ilość");
    
    foreach($this->columnsObjects as $column)
    {
      $tmp = explode("_", $column->getName());
      $this->columns[$column->getName()] = ucfirst($tmp[0]);
    }
    if($request->isMethod('post'))
    {
      $this->column = $request->getParameter('column');
      $this->pattern = $request->getParameter('pattern');
      $this->parametersCount = $this->columnsObjects->count();
      $this->itemsExtraFields = array();
      
      $this->quantityUnit = $category->getQuantityUnit();
      $this->items = StoreItem::searchItems($category, $this->column, $this->pattern);
      
      // Ładowanie wartości kolumn dodatkowych (parameters)
      StoreItem::fillExtraFields($this->items, $this->columnsObjects, $this->itemsExtraFields);
    }

    $this->setLayout(PACore::getLayoutsDir()."/clear");
  }
}

